const fs = require('fs');
const path = require('path');
const mqtt = require('mqtt')

let username = "admin"
let password = "nttieren0513"

// iot生产环境
let connectUrl = 'wss://iot.ironmanapi.com:8084/mqtt'
// iot测试环境
// connectUrl = 'wss://test.ironmanapi.com:8084/mqtt'

let deviceCode = '+'
let productCode = '+'

const clientId = `chj_test_${Math.floor(Math.random() * 100) + 1}`

// 连接选项
const options = {
    clean: true, // true: 清除会话, false: 保留会话
    connectTimeout: 15000, // 超时时间
    clientId,
    username,
    password,
    keepalive: 5
}

const client = mqtt.connect(connectUrl, options)

let subscribeTopics = [
    `outdoor/info/up/${deviceCode}`,
    `outdoor/info/down/${deviceCode}`,

    `outdoor/face/up/${productCode}/${deviceCode}`,
    `outdoor/user/down/${productCode}/${deviceCode}`,

    `thing/down/action/${productCode}/${deviceCode}`,
    `thing/down/up/${productCode}/${deviceCode}`,
    `thing/up/property/${productCode}/${deviceCode}`
]

subscribeTopics = [
    `outdoor/info/up/${deviceCode}`,
    `outdoor/info/down/${deviceCode}`,

    `outdoor/face/up/f52pb598/${deviceCode}`, //握力测试仪
    `outdoor/face/up/zqcyjmxn/${deviceCode}`, //平衡纵跳测试仪
    `outdoor/face/up/0ues6p4r/${deviceCode}`, //体成分心率测试仪

    `outdoor/face/up/e8qeti42/${deviceCode}`, //智慧竞赛车(上肢)
    `outdoor/face/up/w6nc0e2g/${deviceCode}`, //智慧竞赛车(下肢)

    `outdoor/face/up/hgo3omja/${deviceCode}`, //推胸划船双功能训练器
    `outdoor/face/up/bcf1xkh1/${deviceCode}`, //腿部屈伸双功能训练器
    `outdoor/face/up/qtxasflt/${deviceCode}`, //上肢屈伸双功能训练器
    `outdoor/face/up/0mbpchuh/${deviceCode}`, //高拉推举双功能训练器
    `outdoor/face/up/gy7fnzmr/${deviceCode}`, //腹背肌双功能训练器
    `outdoor/face/up/rylq2k5w/${deviceCode}`, //深蹲提踵双功能训练器
]

client.on('connect', () => {
    console.log(`mqtt客户端建立成功，客户端ID【${clientId}】，服务端地址【${connectUrl}】`)
    client.subscribe(subscribeTopics, {qos: 2}, err => {
        if (!err) {
            console.log("mqtt客户端订阅成功", subscribeTopics)
        }
    })
})

let count = 0

client.on('message', (topic, message) => {
    const msg = message.toString();
    if (msg) {
        const messageJson = JSON.parse(msg);
        if (topic.startsWith('outdoor/face/up/')) {
            const {deviceCode, ts, faceBase64} = messageJson
            messageJson.faceBase64 = "base64"
            console.log("↑", topic, "\n", JSON.stringify(messageJson, null, 4))
            count++;
            const fileName = `${ts}_${count}.jpg`;
            const filePath = path.join('tmp', deviceCode);
            if (!fs.existsSync(filePath)) {
                fs.mkdirSync(filePath, {recursive: true});
            }

            const fullFileName = path.join(filePath, fileName);
            fs.writeFileSync(fullFileName, Buffer.from(faceBase64, 'base64'));
        } else if (topic.startsWith("outdoor/user/down/")) {
            const {ts, deviceCode, sportMode, user} = messageJson
            if (user) {
                const {userKey, sex, birthday, weight} = user
                console.log(`${deviceCode} => 用户信息下发成功 => 时间：${ts} 运动模式：${sportMode} 用户ID：${userKey} 性别：${sex} 生日：${birthday} 体重：${weight}`)
            } else {
                console.log(`${deviceCode} => 用户信息下发失败 => 时间：${ts} 运动模式：${sportMode}`)
            }
        } else {
            console.log("↓", topic, "\n", JSON.stringify(messageJson, null, 4))
        }

        console.log('=====================================================================================================================================================================================================================================')
    } else {
        console.error("消息为空")
    }
})
